package com.zhentao.subscription.controller;

import com.zhentao.subscription.common.R;
import com.zhentao.subscription.domain.entity.SubscriptionTask;
import com.zhentao.subscription.service.TaskService;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;

@RestController
@RequestMapping("/api/subscription/files")
@CrossOrigin(origins = "http://localhost:5173")
public class FileController {

    private final TaskService taskService;

    public FileController(TaskService taskService) {
        this.taskService = taskService;
    }

    @GetMapping("/{taskId}")
    public ResponseEntity<?> download(@PathVariable Long taskId) {
        SubscriptionTask task = taskService.getById(taskId);
        if (task == null || task.getFilePath() == null) {
            return ResponseEntity.badRequest().body(R.fail("文件不存在"));
        }
        File file = new File(task.getFilePath());
        if (!file.exists()) {
            return ResponseEntity.badRequest().body(R.fail("文件不存在"));
        }
        FileSystemResource resource = new FileSystemResource(file);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + task.getFileName())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .contentLength(file.length())
                .body(resource);
    }
}

